/* eslint-disable no-plusplus */
/* eslint-disable import/extensions */

import ElEditable from '@components/el-editable';
import {
  commerceSubmitOrder,
  commerceSaveOrder,
  queryOrderInfo,
  orderProductList,
  getOrderAddressList
} from '@api/m_mall_web_v1.js';
import { isObject, throttle } from 'lodash';
import * as CONSTS from './index.const';
import { IndexService } from './index.service';
import { SupplierAndContractComponent } from '~/components/hospital-purchase-order/supplier-and-contract';
import { CarrywayAndAddressComponent } from '~/components/hospital-purchase-order/carryway-and-address';
import { PurchaseProductsListComponent } from '~/components/hospital-purchase-order/hospital-purchase-products-list';

const indexService = new IndexService();
export default {
  components: {
    ElEditable,
    SupplierAndContractComponent,
    CarrywayAndAddressComponent,
    PurchaseProductsListComponent
  },
  inject: ['reload'],
  data() {
    return {
      ...CONSTS,
      active_index: 1,
      dialogVisible: false,
      submit_loading: false,
      bus_model: '1',
      is_edit: false,
      productLoading: false,
      disabled: false,
      // extend_model: [], // 传给form-render所需要的经过整理的内容
      base_extend_data: [], // 从接口拿到的原始的表单配置数据，提交的时候需要
      form_data: {
        active_index: this.active_index,
        supplier: '',
        contract: '',
        carryway: '',
        address: '',
        ordertype: '',
        payway: '',
        address_all: [], // 编辑时要用
        address_full: {},
        remark: '',
        extend: {},
        products: []
      },
      submit_data: {
        busModel: '52',
        busFunction: '1',
        orderType: '', // 这个不要了，但是前端还要传空
        orderTypeId: '', // 订单类型
        payType: '', // 支付方式
        payUse: '', // 支付用途
        transportType: '', // 承运方式
        remark: '', // 备注
        orderCode: '', // 订单编码
        orderDetailId: '', // 订单详情id
        orderId: '', // 订单id
        supplierVo: {
          // 第一步供应商
          // orgId: '',
          orgName: '',
          shortCode: ''
        },
        contractVo: {
          // 第一步-合同
          accountNumber: '',
          customerName: ''
        },
        saveProductVO: [], // 第二步产品
        addressResDto: {} // 第三步-地址
      },
      readonly_formdata: {
        supplier: '',
        contract: ''
      },
      storageAddress: {},
      showCarrywayAndAddress: false,
      thirdExpandVerifyFlag: false, // 把第三步的校验提出来
      isFirstMount: true
    };
  },
  watch: {
    active_index: {
      handler() {
        document.querySelector('.nuxt-main').scrollTop = 0;
      }
    }
  },
  computed: {
    queryParams() {
      return {
        orderId: this.$route.query.orderId,
        reAdd: this.$route.query.reAdd
      };
    }
  },
  mounted() {
    this.initGlobalBtn();
  },
  beforeRouteUpdate(to, from, next) {
    next();
    this.reload();
  },
  created() {
    this.getFullAddress();
  },
  methods: {
    getFullAddress() {
      this.$axios.$post(getOrderAddressList).then(res => {
        this.form_data.address_all = res.payload || [];
        this.getInitialization();
      });
    },
    getInitialization() {
      // 编辑模式
      if (this.queryParams.orderId) {
        if (this.queryParams.reAdd) {
          this.active_index = 2;
        }
        this.productLoading = true;
        this.disabled = true;
        this.is_edit = true;
        this.$axios({
          url: queryOrderInfo,
          method: 'post',
          data: {
            orderId: this.queryParams.orderId
          }
        }).then(res => {
          const result = res.data.payload ? res.data.payload : {};
          result.transportType = result.transportType
            ? `${result.transportType}`
            : result.transportType;
          // 其实这里直接把结果赋值给submit_data就可以了，但是为了某些更改项的对应，还是重新一一赋值一下。
          this.resetDetailInfo(result);
          this.showCarrywayAndAddress = true;
        });
      } else {
        this.showCarrywayAndAddress = true;
      }
    },
    resetDetailInfo(detail) {
      // 最先调用第三步的附加信息，获取其表单框架
      // 先给第二步的详情赋值,其实就是从结果里单独抽出来
      let judgeAddress = null;
      if (this.form_data.address_all.length > 0) {
        judgeAddress = this.form_data.address_all.find(
          item => item.id === detail.addressResDto.id
        );
      } else {
        judgeAddress = undefined;
      }
      const readOnlyDetail = {
        orgName: detail.supplierVo.orgName,
        contract: detail.contractVo.customerName
      };
      this.readonly_formdata = indexService.mappingOrderDetailReadonly(
        readOnlyDetail
      );
      // 然后给submit_data赋值，多说一下，submit_data是最后提交的经过整理的内容，而form_data是未经整理的散乱的。
      // 换句话说，submit_data是给后端接口用的，form_data是给前端自己用的。
      this.submit_data = {
        busModel: '52',
        orderType: '', // 订单类型
        orderTypeId: detail.orderTypeId,
        payType: detail.payType, // 支付方式
        payUse: detail.payUse, // 支付用途
        transportType: detail.transportType || '', // 承运方式
        remark: detail.remark, // 备注
        orderCode: detail.orderCode, // 订单编码
        orderDetailId: detail.orderDetailId, // 订单详情id
        orderId: this.queryParams.reAdd ? '' : detail.orderId, // 订单id
        // 第一步供应商
        supplierVo: {
          // orgId: detail.supplierVo.vendorCode,
          orgName: detail.supplierVo.vendorName,
          shortCode: detail.supplierVo.vendorCode
        },
        contractVo: {
          accountNumber: detail.contractVo.hospitalCode,
          customerName: detail.contractVo.hospitalName
        }, // 第一步-合同
        addressResDto: judgeAddress !== undefined ? detail.addressResDto : {} // 第三步-地址
        // addressResDto: detail.addressResDto // 第三步-地址
      };
      // 还要给前端数据form_data赋值
      this.form_data = {
        active_index: this.active_index,
        detail_id: this.submit_data.orderDetailId,
        supplier: this.submit_data.supplierVo.shortCode,
        contract: this.submit_data.contractVo.accountNumber,
        carryway: this.submit_data.transportType,
        address: this.submit_data.addressResDto.userAddressId || '',
        ordertype: this.submit_data.orderTypeId,
        payway: this.submit_data.payType,
        address_full: this.submit_data.addressResDto,
        remark: this.submit_data.remark,
        products: []
      };
      // 额外获取第二步的产品数据，orderDetailId不从路由拿去，只从这个详情数据中取。
      // 路由实际参数只有orderId是有用的
      this.getProductsList(this.form_data.detail_id);
    },
    // 额外单独获取产品详情
    getProductsList(id) {
      this.$axios({
        url: orderProductList,
        method: 'post',
        data: {
          orderDetailId: id,
          page: 1,
          pageSize: 9999
        }
      })
        .then(res => {
          const result = res.data.payload.content.length
            ? res.data.payload.content
            : [];
          // 毫无意义的数据转换，为后端各接口返回值不匹配买单
          result.forEach(item => {
            const newItem = item;
            newItem.factoryItemNum = item.originalProductCode;
            newItem.itemNum = item.productCode;
            newItem.itemName = newItem.productNameCN;
            newItem.specs = item.specs;
            newItem.lineNum = newItem.productCount;
            newItem.primaryUnitOfMeasureName = newItem.productUnitName;
            newItem.manufacturerName = newItem.originalFactoryName;
            newItem.price = newItem.referencePrice || '';
            // item.productLineName = item.productLineName;
          });
          this.submit_data.saveProductVO = result;
          this.form_data.products = result;
        })
        .finally(() => {
          this.productLoading = false;
          this.disabled = false;
        });
    },
    initGlobalBtn() {
      const btnObj = {
        type: 'btn',
        arr: []
      };
      const saveDraftBtn = {
        val: '暂存',
        handle: this.onSaveDraft
      };
      const prevBtn = {
        type: 'primary',
        val: '上一步',
        handle: this.onPrev
      };
      const nextBtn = {
        type: 'primary',
        val: '下一步',
        handle: this.onNext
      };
      const submitBtn = {
        type: 'primary',
        val: '提交',
        handle: this.showConfirmDialog
      };
      // if (this.active_index !== 1) {
      //   btnObj.arr.push(prevBtn);
      // }
      if (
        (!this.queryParams.reAdd && this.active_index !== 1) ||
        (this.queryParams.reAdd && this.active_index === 3)
      ) {
        btnObj.arr.push(prevBtn);
      }
      if (this.active_index !== 3) {
        btnObj.arr.push(nextBtn);
      } else {
        btnObj.arr.push(submitBtn);
      }
      btnObj.arr.push(saveDraftBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    showConfirmDialog() {
      const verifyResult = indexService.verifyStep(3, this.form_data);
      if (verifyResult.pass === true) {
        this.$msgbox({
          title: '提交订单',
          message: '确认是否提交订单？',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.onSubmit(instance, done);
            } else {
              done();
            }
          }
        });
        this.saveTheData();
      } else {
        this.$notify({
          title: '必填项',
          message: verifyResult.message,
          type: 'warning'
        });
      }
    },
    onSubmit: throttle(
      // eslint-disable-next-line func-names
      function(instance, done) {
        const newInstance = instance;
        this.submit_data.addressResDto = this.storageAddress;
        this.submit_loading = true;
        newInstance.confirmButtonLoading = true;
        newInstance.confirmButtonText = '提交中...';
        this.$axios({
          url: commerceSubmitOrder,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$router.push('/hospital-purchase-order/list');
              this.$message({
                message: '订单提交成功',
                type: 'success'
              });
            }
          })
          .catch(err => {
            if (err.data.code === '200001') {
              this.$router.push('/hospital-purchase-order/list');
            }
          })
          .finally(() => {
            this.dialogVisible = false;
            this.submit_loading = false;
            newInstance.confirmButtonLoading = false;
            done();
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    async onNext() {
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.form_data
      );
      if (verifyResult.pass === true) {
        if (this.active_index++ >= 3) this.active_index = 3;
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
      this.initGlobalBtn();
    },
    onPrev() {
      if (this.active_index-- <= 1) this.active_index = 1;
      this.initGlobalBtn();
    },
    onSupplierAndContractChange(val) {
      this.readonly_formdata = indexService.mappingOrderDetailReadonly(val);
      this.submit_data.supplierVo = Object.assign(
        this.submit_data.supplierVo || {},
        val.suppliy
      );
      this.submit_data.contractVo = Object.assign(
        this.submit_data.contractVo || {},
        val.contract
      );
      // 这里要清空一些特殊的数据
      // 第2步的产品列表和第三步的订单类型
      if (!this.isFirstMount) {
        if (this.form_data.products.length) {
          this.submit_data.saveProductVO = null;
          this.form_data.products = [];
        }

        if (this.form_data.ordertype) {
          this.form_data.ordertype = '';
          if (this.submit_data.orderTypeId) this.submit_data.orderTypeId = '';
        }
      }
    },
    onAddressChanged(val) {
      // 地址需要全量数据
      this.form_data.address_full = val;
      this.submit_data.addressResDto = Object.assign(
        this.submit_data.addressResDto || {},
        val
      );
      this.storageAddress = this.submit_data.addressResDto;
    },
    saveTheData() {
      // 通过sync和update更新products数据，所以这里要赋值以下，该操作意图等同于onSupplierAndContractChange方法。
      // 赋值第二步选择产品部分数据
      this.submit_data.saveProductVO = this.form_data.products;
      // 复制第三步的三个选项部分（订单类型，承运方式，支付方式，以及备注）
      this.submit_data.transportType = this.form_data.carryway; // 承运方式
      this.submit_data.remark = this.form_data.remark; // 备注
      this.submit_data.addressResDto = this.storageAddress;
    },
    splitSubmitDataBySteps() {
      const curStep = this.active_index; // 当前步骤
      // 这里跟submit_data一模一样，下面选择性的赋值
      const splitSubmitData = {
        busModel: '52',
        busFunction: '1',
        orderType: '', // 订单类型
        orderTypeId: '', // 订单类型
        payType: '', // 支付方式
        payUse: '', // 支付用途
        transportType: Number(this.submit_data.transportType), // 承运方式
        remark: this.submit_data.remark, // 备注
        orderCode: this.submit_data.orderCode, // 订单编码
        orderDetailId: this.submit_data.orderDetailId, // 订单详情id
        orderId: this.submit_data.orderId, // 订单id
        // 第一步供应商
        supplierVo: {
          // orgId: '',
          orgName: '',
          shortCode: ''
        },
        contractVo: {}, // 第一步-合同
        saveProductVO: [], // 第二步产品
        addressResDto: null // 第三步-地址
      };
      // 第一步
      // eslint-disable-next-line default-case
      switch (curStep) {
        // 第一步，只存第一步的合同和供应商
        case 1:
          splitSubmitData.supplierVo = {
            vendorCode: this.submit_data.supplierVo.shortCode,
            vendorName: this.submit_data.supplierVo.orgName
          };
          splitSubmitData.contractVo = {
            hospitalCode: this.submit_data.contractVo.accountNumber,
            hospitalName: this.submit_data.contractVo.customerName
          };
          break;
        // 除了第一步的，还额外需要产品部分
        case 2:
          splitSubmitData.supplierVo = {
            vendorCode: this.submit_data.supplierVo.shortCode,
            vendorName: this.submit_data.supplierVo.orgName
          };
          splitSubmitData.contractVo = {
            hospitalCode: this.submit_data.contractVo.accountNumber,
            hospitalName: this.submit_data.contractVo.customerName
          };
          this.submit_data.saveProductVO.forEach(item => {
            const newItem = item;
            newItem.originalProductCode = newItem.factoryItemNum;
            newItem.productCode = newItem.itemNum;
            newItem.productName = newItem.itemName;
            newItem.originalFactoryName = newItem.manufacturerName;
            newItem.originalFactoryCode = newItem.manufacturerCode;
            newItem.attribute1 = newItem.specs;
            newItem.productUnitName = newItem.primaryUnitOfMeasureName;
            // item.productLineName = item.productLineName
          });
          splitSubmitData.saveProductVO = this.submit_data.saveProductVO;
          break;
        // 第三步就比较简单了
        case 3:
          splitSubmitData.supplierVo = {
            vendorCode: this.submit_data.supplierVo.shortCode,
            vendorName: this.submit_data.supplierVo.orgName
          };
          splitSubmitData.contractVo = {
            hospitalCode: this.submit_data.contractVo.accountNumber,
            hospitalName: this.submit_data.contractVo.customerName
          };
          this.submit_data.saveProductVO.forEach(item => {
            const newItem = item;
            newItem.originalProductCode = newItem.factoryItemNum;
            newItem.productCode = newItem.itemNum;
            newItem.productName = newItem.itemName;
            newItem.originalFactoryName = newItem.manufacturerName;
            newItem.originalFactoryCode = newItem.manufacturerCode;
            newItem.attribute1 = newItem.specs;
            newItem.productUnitName = newItem.primaryUnitOfMeasureName;
            // item.productLineName = item.productLineName
          });
          splitSubmitData.saveProductVO = this.submit_data.saveProductVO;
          splitSubmitData.addressResDto = this.submit_data.addressResDto;
          break;
      }
      return splitSubmitData;
    },
    saveProgress: throttle(
      // eslint-disable-next-line func-names
      function() {
        const loading = this.$loading({
          lock: true,
          text: '正在暂存，请稍后...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.1)'
        });
        this.saveTheData();
        this.$axios({
          url: commerceSaveOrder,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            const order = isObject(res.data.payload) ? res.data.payload : {};
            this.submit_data.orderId = order.orderId;
            this.submit_data.orderDetailId = order.orderDetailId;
            this.submit_data.orderCode = order.orderCode;
            this.$message({
              type: 'success',
              message: '暂存成功'
            });
          })
          .catch(() => {
            this.$message({
              type: 'warning',
              message: '暂存失败'
            });
          })
          .finally(() => {
            loading.close();
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    async onSaveDraft() {
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.form_data
      );
      if (verifyResult.pass === true) {
        this.saveProgress();
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
    }
  }
};
